package com.wsh.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsh.dto.sys.RoleMenuDto;
import com.wsh.sys.RoleMenuService;
import com.wsh.utils.SecurityUtils;
import com.wsh.entity.sys.RoleMenuEntity;
import com.wsh.mapper.sys.RoleMenuDao;
import com.wsh.utils.PageUtils;
import com.wsh.vo.sys.RoleMenuVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 王思涵
 * @Date 2020/01/11
 * @Version 1.0
 * @Desciption 角色菜单关联业务接口实现
 **/
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuDao, RoleMenuEntity> implements RoleMenuService {

    @Override
    public IPage<RoleMenuEntity> getList(RoleMenuDto roleMenuDto) {
        // 分页数据处理
        IPage<RoleMenuEntity> pages = PageUtils.getPage(roleMenuDto);

        // 分页查询处理
        IPage<RoleMenuEntity> page =  baseMapper.selectPage(pages, new QueryWrapper<RoleMenuEntity>());

        return page;
    }

    @Override
    public boolean saveRoleMenus(RoleMenuVo roleMenuVo) {
        List<RoleMenuEntity> roleMenuEntities = new ArrayList<>();

        String roleId = roleMenuVo.getRoleId();

        RoleMenuVo findRoleMenuVo = getMenusByRole(roleId);
        if (findRoleMenuVo != null && findRoleMenuVo.getMenus().length > 0) {
            baseMapper.removeRole(findRoleMenuVo);
        }

        // 超级管理员 标识
        if (SecurityUtils.isAdmin(roleId)) {
            roleMenuEntities.add(new RoleMenuEntity(roleId, "admin"));
        }

        for (String menuId: roleMenuVo.getMenus()) {
            roleMenuEntities.add(new RoleMenuEntity(roleId, menuId));
        }
        return saveBatch(roleMenuEntities);
    }

    @Override
    public RoleMenuVo getMenusByRole(String roleId) {
        List<RoleMenuEntity> roleMenuEntities = getMenusByRoleId(roleId);
        List<String> menus = new ArrayList<>();
        for (RoleMenuEntity roleMenuEntity: roleMenuEntities) {
            menus.add(roleMenuEntity.getMenuId());
        }
        return new RoleMenuVo(roleId, menus.toArray(new String[menus.size()]));
    }

    public List<RoleMenuEntity> getMenusByRoleId(String roleId) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("role_id", roleId);
        List<RoleMenuEntity> roleMenuEntities = baseMapper.selectByMap(maps);
        return roleMenuEntities;
    }
}
